package org.ligson.spark.rdd.demo;

import org.apache.spark.api.java.JavaPairRDD;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.JavaSparkContext;
import org.apache.spark.api.java.function.FlatMapFunction;
import org.apache.spark.api.java.function.Function2;
import org.apache.spark.api.java.function.PairFunction;
import org.apache.spark.api.java.function.VoidFunction;
import org.ligson.spark.util.SparkContextUtil;
import scala.Tuple2;

import java.util.Arrays;
import java.util.Iterator;

public class HelloSpark {

    public static void main(String[] args) {
        JavaSparkContext jsc = SparkContextUtil.getLocalContext();
        JavaRDD<String> pom = jsc.textFile("./src/main/resources/text.txt");
        System.out.println(pom.count());
        //将函数应用于RDD中的每个元素，将返回的迭代器的所有内容构成新的RDD，通常用来切分单词。与map的区别是：这个函数返回的值是list的一个，去除原有的格式
        JavaRDD<String> words = pom.flatMap(new FlatMapFunction<String, String>() {
            public Iterator<String> call(String s) throws Exception {
                return Arrays.asList(s.split(" ")).iterator();
            }
        });
        System.out.println(words.count());
        //Spark为包含键值对类型的RDD提供了一些专有的操作，这些RDD称为pair RDD。当需要把一个普通的RDD转为pair RDD时，可以调用map()函数来实现。
        JavaPairRDD<String, Integer> word2int = words.mapToPair(new PairFunction<String, String, Integer>() {
            public Tuple2<String, Integer> call(String word) throws Exception {
                return new Tuple2<String, Integer>(word, 1);
            }
        });
        word2int.foreach(new VoidFunction<Tuple2<String, Integer>>() {
            public void call(Tuple2<String, Integer> tuple2) throws Exception {
                System.out.println("tuple:" + tuple2._1 + "=" + tuple2._2);
            }
        });
        System.out.println(word2int.count());
        //是使用一个相关的函数来合并每个key的value的值的一个算子（那么主干就是reduceByKey是个算子/函数）。
        JavaPairRDD<String, Integer> res = word2int.reduceByKey(new Function2<Integer, Integer, Integer>() {
            public Integer call(Integer a, Integer b) throws Exception {
                System.out.println(a + "--" + b);
                return a + b;
            }
        });
        res.foreach(new VoidFunction<Tuple2<String, Integer>>() {
            public void call(Tuple2<String, Integer> t) throws Exception {
                System.out.println(t._1 + " : " + t._2);
            }
        });

    }
}